﻿using SaaS.Cache.Auths;
using SaaS.Core;
using System;
using System.Collections.Generic;
using System.Text;
using XCore.Dependency;
using XCore.Helper;

namespace SaaS.Cache.Auths
{
    /// <summary>
    /// 客户端用户授权缓存服务
    /// </summary>
    public class UserAuthCacheService : AuthCacheServiceBase, ISingletonDependency
    {
        private const string USER_TOKEN = "USER_TOKEN_";

        /// <summary>
        /// 获取用户token
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string GetUserToken(int userId)
        {
            return MemoryHelper.Get(USER_TOKEN + userId, () =>
            {
                return base.GetToken(USER_TOKEN, userId);
            });
        }
        /// <summary>
        /// 检查用户token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool CheckUserToken(int userId, string token)
        {
            return this.GetUserToken(userId) == token;
        }
        /// <summary>
        /// 移除用户token
        /// </summary>
        /// <param name="userId"></param>
        public void RemoveUserToken(int userId)
        {
            this.RemoveToken(USER_TOKEN, userId);
            MemoryHelper.Remove(USER_TOKEN + userId);
        }
        /// <summary>
        /// 设置用户token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        public void SetUserToken(int userId, string token)
        {
            base.SetToken(USER_TOKEN, userId, token);
            MemoryHelper.Set(USER_TOKEN + userId, TimeSpan.FromHours(CoreSetting.Expire), token);
        }

    }
}
